import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import i18n from '@/i18n'

// 主题类型定义
export type ThemeMode = 'light' | 'dark' | 'auto' | 'sunrise'
export type CustomTheme = 'default' | 'blue' | 'green' | 'purple' | 'orange'
export type Language = 'zh-CN' | 'en-US'
export type LayoutMode = 'sidebar' | 'horizontal'
export type BackgroundEffect = 'none' | 'particles' | 'bubbles' | 'grid'

// 主题配置接口
interface AppConfig {
  mode: ThemeMode
  customTheme: CustomTheme
  followSystem: boolean
  language: Language
  layoutMode: LayoutMode
  backgroundEffect: BackgroundEffect
  backgroundEffectIntensity: number
}

// 系统主题检测
const getSystemTheme = (): 'light' | 'dark' => {
  if (typeof window !== 'undefined' && window.matchMedia) {
    return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
  }
  return 'light'
}

// 日出日落主题检测 - 7:00-21:00为白天，其余为夜间
const getSunriseTheme = (): 'light' | 'dark' => {
  const hour = new Date().getHours()
  return (hour >= 7 && hour < 21) ? 'light' : 'dark'
}

/**
 * 主题管理Store
 */
export const useThemeStore = defineStore('theme', () => {
  // ==================== 状态数据 ====================
  
  const themeMode = ref<ThemeMode>('auto')
  const customTheme = ref<CustomTheme>('default')
  const followSystem = ref(true)
  const systemTheme = ref<'light' | 'dark'>(getSystemTheme())
  const language = ref<Language>('zh-CN')
  const layoutMode = ref<LayoutMode>('sidebar')
  const backgroundEffect = ref<BackgroundEffect>('particles')
  const backgroundEffectIntensity = ref<number>(50)

  // 日出日落模式定时器
  let sunriseTimer: NodeJS.Timeout | null = null

  // ==================== 计算属性 ====================
  
  // 当前实际应用的主题模式
  const currentTheme = computed(() => {
    if (themeMode.value === 'sunrise') {
      return getSunriseTheme()
    }
    if (themeMode.value === 'auto' || followSystem.value) {
      return systemTheme.value
    }
    return themeMode.value
  })

  // 主题类名
  const themeClass = computed(() => {
    const mode = currentTheme.value
    const custom = customTheme.value
    return `theme-${mode} theme-${custom}`
  })

  // 是否为暗色主题
  const isDark = computed(() => currentTheme.value === 'dark')

  // ==================== 方法 ====================
  
  /**
   * 设置主题模式
   */
  const setThemeMode = (mode: ThemeMode) => {
    themeMode.value = mode
    followSystem.value = mode === 'auto'

    // 管理日出日落模式定时器
    if (mode === 'sunrise') {
      startSunriseTimer()
    } else {
      stopSunriseTimer()
    }

    saveThemeConfig()
    applyTheme()
  }

  /**
   * 设置自定义主题
   */
  const setCustomTheme = (theme: CustomTheme) => {
    customTheme.value = theme
    saveThemeConfig()
    applyTheme()
  }

  /**
   * 设置语言
   */
  const setLanguage = (lang: Language) => {
    language.value = lang
    i18n.global.locale.value = lang
    saveThemeConfig()
  }

  /**
   * 设置布局模式
   */
  const setLayoutMode = (mode: LayoutMode) => {
    layoutMode.value = mode
    saveThemeConfig()
  }

  /**
   * 设置背景动效
   */
  const setBackgroundEffect = (effect: BackgroundEffect) => {
    backgroundEffect.value = effect
    saveThemeConfig()
  }

  /**
   * 设置背景动效强度
   */
  const setBackgroundEffectIntensity = (intensity: number) => {
    backgroundEffectIntensity.value = Math.max(0, Math.min(100, intensity))
    saveThemeConfig()
  }

  /**
   * 切换主题模式 - 支持四种模式循环切换
   */
  const toggleTheme = () => {
    const modes: ThemeMode[] = ['light', 'dark', 'auto', 'sunrise']
    const currentIndex = modes.indexOf(themeMode.value)
    const nextIndex = (currentIndex + 1) % modes.length
    setThemeMode(modes[nextIndex])
  }

  /**
   * 应用主题到DOM
   */
  const applyTheme = () => {
    if (typeof document === 'undefined') return

    const html = document.documentElement
    const body = document.body

    // 移除所有主题类
    html.className = html.className.replace(/theme-\w+/g, '').trim()
    body.className = body.className.replace(/theme-\w+/g, '').trim()

    // 添加新的主题类
    const classes = themeClass.value.split(' ')
    html.classList.add(...classes)
    body.classList.add(...classes)

    // 同步主题色到Element Plus变量
    applyCustomThemeColors()

    // 设置Element Plus主题
    if (isDark.value) {
      html.classList.add('dark')
    } else {
      html.classList.remove('dark')
    }

    // 更新meta标签（移动端状态栏）
    updateMetaThemeColor()
  }

  /**
   * 将自定义主题色同步到Element Plus变量
   */
  const applyCustomThemeColors = () => {
    if (typeof document === 'undefined') return

    const root = document.documentElement

    // 主题色映射
    const themeColors = {
      default: {
        primary: '#0ea5e9',
        primaryLight: '#38bdf8',
        primaryDark: '#0284c7'
      },
      blue: {
        primary: '#3b82f6',
        primaryLight: '#60a5fa',
        primaryDark: '#2563eb'
      },
      green: {
        primary: '#22c55e',
        primaryLight: '#4ade80',
        primaryDark: '#16a34a'
      },
      purple: {
        primary: '#8b5cf6',
        primaryLight: '#a78bfa',
        primaryDark: '#7c3aed'
      },
      orange: {
        primary: '#f59e0b',
        primaryLight: '#fbbf24',
        primaryDark: '#d97706'
      }
    }

    const colors = themeColors[customTheme.value] || themeColors.default

    // 设置Element Plus主色变量
    root.style.setProperty('--el-color-primary', colors.primary)
    root.style.setProperty('--el-color-primary-light-3', colors.primaryLight)
    root.style.setProperty('--el-color-primary-light-5', colors.primaryLight)
    root.style.setProperty('--el-color-primary-light-7', colors.primaryLight)
    root.style.setProperty('--el-color-primary-light-8', colors.primaryLight)

    // 处理透明度颜色
    const primaryRgb = hexToRgb(colors.primary)
    if (primaryRgb) {
      root.style.setProperty('--el-color-primary-light-9', `rgba(${primaryRgb.r}, ${primaryRgb.g}, ${primaryRgb.b}, 0.1)`)
    }

    root.style.setProperty('--el-color-primary-dark-2', colors.primaryDark)
  }

  /**
   * 将十六进制颜色转换为RGB
   */
  const hexToRgb = (hex: string) => {
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
    return result ? {
      r: parseInt(result[1], 16),
      g: parseInt(result[2], 16),
      b: parseInt(result[3], 16)
    } : null
  }

  /**
   * 更新meta主题色
   */
  const updateMetaThemeColor = () => {
    if (typeof document === 'undefined') return

    let metaThemeColor = document.querySelector('meta[name="theme-color"]')
    if (!metaThemeColor) {
      metaThemeColor = document.createElement('meta')
      metaThemeColor.setAttribute('name', 'theme-color')
      document.head.appendChild(metaThemeColor)
    }

    // 根据主题设置状态栏颜色
    const color = isDark.value ? '#1a1a1a' : '#ffffff'
    metaThemeColor.setAttribute('content', color)
  }

  /**
   * 启动日出日落模式定时器
   */
  const startSunriseTimer = () => {
    stopSunriseTimer() // 先清除已有定时器

    // 每分钟检查一次时间变化
    sunriseTimer = setInterval(() => {
      if (themeMode.value === 'sunrise') {
        applyTheme()
      }
    }, 60000) // 60秒检查一次
  }

  /**
   * 停止日出日落模式定时器
   */
  const stopSunriseTimer = () => {
    if (sunriseTimer) {
      clearInterval(sunriseTimer)
      sunriseTimer = null
    }
  }

  /**
   * 监听系统主题变化
   */
  const watchSystemTheme = () => {
    if (typeof window === 'undefined' || !window.matchMedia) return

    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')

    const handleChange = (e: MediaQueryListEvent) => {
      systemTheme.value = e.matches ? 'dark' : 'light'
      if (followSystem.value) {
        applyTheme()
      }
    }

    mediaQuery.addEventListener('change', handleChange)

    // 返回清理函数
    return () => {
      mediaQuery.removeEventListener('change', handleChange)
    }
  }

  /**
   * 保存主题配置
   */
  const saveThemeConfig = () => {
    const config: AppConfig = {
      mode: themeMode.value,
      customTheme: customTheme.value,
      followSystem: followSystem.value,
      language: language.value,
      layoutMode: layoutMode.value,
      backgroundEffect: backgroundEffect.value,
      backgroundEffectIntensity: backgroundEffectIntensity.value
    }
    localStorage.setItem('app-config', JSON.stringify(config))
  }

  /**
   * 加载主题配置
   */
  const loadThemeConfig = () => {
    try {
      const saved = localStorage.getItem('app-config')
      if (saved) {
        const config: AppConfig = JSON.parse(saved)
        themeMode.value = config.mode || 'auto'
        customTheme.value = config.customTheme || 'default'
        followSystem.value = config.followSystem ?? true
        language.value = config.language || 'zh-CN'
        layoutMode.value = config.layoutMode || 'sidebar'
        backgroundEffect.value = config.backgroundEffect || 'particles'
        backgroundEffectIntensity.value = config.backgroundEffectIntensity ?? 50
        i18n.global.locale.value = language.value
      }
    } catch (error) {
      console.warn('加载应用配置失败:', error)
    }
  }

  /**
   * 初始化主题
   */
  const initTheme = () => {
    loadThemeConfig()
    systemTheme.value = getSystemTheme()

    // 如果是日出日落模式，启动定时器
    if (themeMode.value === 'sunrise') {
      startSunriseTimer()
    }

    applyTheme()
    watchSystemTheme()
  }

  // ==================== 监听器 ====================
  
  // 监听主题变化，自动应用
  watch([themeMode, customTheme, systemTheme], () => {
    applyTheme()
  })

  // ==================== 返回状态和方法 ====================
  
  return {
    // 状态
    themeMode,
    customTheme,
    followSystem,
    systemTheme,
    language,
    layoutMode,
    backgroundEffect,
    backgroundEffectIntensity,

    // 计算属性
    currentTheme,
    themeClass,
    isDark,

    // 方法
    setThemeMode,
    setCustomTheme,
    setLanguage,
    setLayoutMode,
    setBackgroundEffect,
    setBackgroundEffectIntensity,
    toggleTheme,
    applyTheme,
    initTheme,
    saveThemeConfig,
    loadThemeConfig
  }
})
